package billings.classtasks.tasks;

import java.util.List;

import billings.classtasks.ClassTasksActivity;
import billings.classtasks.R;
import billings.classtasks.R.id;
import billings.classtasks.R.layout;
import billings.classtasks.classes.Class;
import billings.classtasks.classes.ClassDAO;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class CreateTask extends Activity implements OnClickListener {
	
	private EditText title;
	private EditText description;
	private DatePicker dueDate;
	private RadioGroup classesRadio;
	
	private Button create;
	private Button cancel;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_task);
        ClassDAO cDAO = new ClassDAO(this);
        cDAO.open();
        
        title = (EditText)findViewById(R.id.taskTitle);
        description = (EditText)findViewById(R.id.taskDescription);
        dueDate = (DatePicker)findViewById(R.id.taskDueDate);
        
        create = (Button)findViewById(R.id.taskCreate);
        cancel = (Button)findViewById(R.id.taskCancel);
        
        create.setOnClickListener(this);
        cancel.setOnClickListener(this);
        
        classesRadio = (RadioGroup)findViewById(R.id.classRadio);
        List<Class> classes = cDAO.getAllClasses();
        
        int selectedRadio = -1;
        Bundle extras = getIntent().getExtras();
        if(extras != null && extras.getInt("classId") != 0){
        	selectedRadio = extras.getInt("classId");
        }
        
        for(Class c : classes){
        	RadioButton rb = new RadioButton(this);
        	rb.setText(c.toString());
        	rb.setId((int)c.getId());
        	
        	if(selectedRadio != -1 && selectedRadio == c.getId()){
        		rb.setChecked(true);
        	}
        	
        	classesRadio.addView(rb);
        }
        
        cDAO.close();
	}

	public void onClick(View v) {
		Intent i;
		switch(v.getId()){
		case R.id.taskCreate:
			i = new Intent(this, ClassTasksActivity.class);
			Bundle taskVals = new Bundle();
			taskVals.putString("title", title.getText().toString());
			taskVals.putString("description", description.getText().toString());
			taskVals.putString("dueDate", dueDate.getMonth() + "/" + dueDate.getDayOfMonth() + "/" + dueDate.getYear());
			taskVals.putInt("classId", classesRadio.getCheckedRadioButtonId());
			i.putExtra("taskVals", taskVals);
			i.putExtra("action", "create");
			startActivity(i);
			break;
		case R.id.taskCancel:
			i = new Intent(this, ClassTasksActivity.class);
			startActivity(i);
			break;
		}
	}

}
